package org.jeecg.modules.demo.task.manager;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.task.controller.TTaskController;
import org.jeecg.modules.demo.task.entity.TTask;
import org.jeecg.modules.demo.task.entity.TTaskCron;
import org.jeecg.modules.demo.task.mapper.TTaskMapper;
import org.jeecg.modules.demo.task.mapper.TaskMapper;
import org.jeecg.modules.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

/**
 * @ClassName: DynamicTaskManager
 * @Description:
 * @Author: 墨渍
 * @Date: 2025/4/17 9:44
 **/
@Component
@Slf4j
public class DynamicTaskManager {


    @Autowired
    private ThreadPoolTaskScheduler scheduler;
    @Resource
    TaskMapper taskMapper;

    // 保存已注册任务
    private final Map<Long, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();
    private final Map<String, String> cronMap = new ConcurrentHashMap<>();

    public Map<Long, ScheduledFuture<?>> findFutureMap(){
        return futureMap;
    }
    public Map<String, String> findCronMap(){
        return cronMap;
    }

    @Autowired
    private MyComTaskRunner jobRunner;

    /**
     * 启动所有启用的任务（服务启动时）
     */
    @PostConstruct
    public void initTask() {
        log.info("⏳ 初始化任务调度器...");
        List<TTask> allTask = taskMapper.findAllTask();
        List<TTaskCron> taskCron = taskMapper.findTaskCron();
        taskCron.forEach(e->{
            String level = e.getLevel();
            String cron = e.getCron();
            cronMap.put(level, cron);
        });
        List<TTask> allRunTask = allTask.stream().filter(e -> e.getType() == 1).collect(Collectors.toList());
        allRunTask.forEach(this::startTask);
    }

    public void startTask(TTask job) {
        if (futureMap.containsKey(job.getId())) {
            return; // 已启动
        }
        SysUser userById = taskMapper.findUserById(job.getUserId());
        job.setToken(userById.getToken());
        log.info("小红书笔记id为：{}，启动成功",job.getNoteId());
        ScheduledFuture<?> future = scheduler.schedule(() -> {
            jobRunner.execute(job); // 执行业务逻辑
        }, new CronTrigger(cronMap.get(job.getTaskTime())));
        futureMap.put(job.getId(), future);
    }

    public void stopTask(Long taskId) {
        ScheduledFuture<?> future = futureMap.remove(taskId);
        if (future != null) {
            future.cancel(true);
        }
    }

    public void refreshTask(TTask job) {
        stopTask(job.getId());
        if (job.getType()==0) {
            startTask(job);
        }
    }
}
